window.console = window.console || (function(){
    var c = {}; c.log = c.warn = c.debug = c.info = c.error = c.time = c.dir = c.profile
        = c.clear = c.exception = c.trace = c.assert = function(){};
    return c;
})();
// 对Date的扩展，将 Date 转化为指定格式的String
// 月(M)、日(d)、小时(h)、分(m)、秒(s)、季度(q) 可以用 1-2 个占位符，
// 年(y)可以用 1-4 个占位符，毫秒(S)只能用 1 个占位符(是 1-3 位的数字)
// 例子：
// (new Date()).Format("yyyy-MM-dd hh:mm:ss.S") ==> 2006-07-02 08:09:04.423
// (new Date()).Format("yyyy-M-d h:m:s.S")      ==> 2006-7-2 8:9:4.18
Date.prototype.Format = function(fmt)
{ //author: meizz
    var o = {
        "M+" : this.getMonth()+1,                 //月份
        "d+" : this.getDate(),                    //日
        "h+" : this.getHours(),                   //小时
        "m+" : this.getMinutes(),                 //分
        "s+" : this.getSeconds(),                 //秒
        "q+" : Math.floor((this.getMonth()+3)/3), //季度
        "S"  : this.getMilliseconds()             //毫秒
    };
    if(/(y+)/.test(fmt))
        fmt=fmt.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length));
    for(var k in o)
        if(new RegExp("("+ k +")").test(fmt))
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));
    return fmt;
}
//解决浏览器窗口变化时表格头部无法自适应的问题
$(window).resize(function () {
    if($('#table').bootstrapTable!=undefined)
    {
        $('#table').bootstrapTable('resetView');
    }
    
});
//加载时适应浏览器高度
$(document).ready(function() {
    //模块尺寸
   	$('.div-menu').css('height', $(window).height() - 42);
});
//改变窗体大小时适应浏览器高度
$(window).resize(function() {
    //模块尺寸
   	$('.div-menu').css('height', $(window).height() - 42);
});

/////////////////////////////////////////////////////////////////////
///全局变量
///标准
//var globalUrl = "http://192.168.60.67:8099/";
//var globalUrl = "http://192.168.10.7:8061/";//company_test_HuBei
var globalUrl = "http://192.168.10.8:8009/";//company_test_JiangSu
//var globalUrl = "http://192.168.60.161/TBMS/";//hll_test

var globalUserCode = $.cookie("Custom-Auth-Name");
var funUrl,funName ;

///重写$.ajax
(function($){
    //备份jquery的ajax方法
    var _ajax=$.ajax;
    $.support.cors = true;
    //重写jquery的ajax方法
    $.ajax=function(opt){
        //备份opt中error和success方法
        var fn = {
            error:function(XMLHttpRequest, textStatus, errorThrown){},
            beforeSend:function(XMLHttpRequest){},
            complete:function(){},
            success:function(data, textStatus){}
        };
        if(opt.error){
            fn.error=opt.error;
        }
        if(opt.beforeSend){
            fn.beforeSend=opt.beforeSend;
        }
        if(opt.complete){
            fn.complete=opt.complete;
        }
        if(opt.success){
            fn.success=opt.success;
        }
        //扩展增强处理
        var _opt = $.extend(opt,{
            error:function(XMLHttpRequest, textStatus, errorThrown){
                //错误方法增强处理
                if(XMLHttpRequest.status=="403"){
                    alert("安全认证失败，请重新登录");
                    location.href="./login.html";
                }else{
                    //alert("返回错误码："+XMLHttpRequest.status+errorThrown);
                    fn.error(XMLHttpRequest, textStatus, errorThrown);
                }
            },
            beforeSend : function(XMLHttpRequest) {
                XMLHttpRequest.setRequestHeader("Custom-Auth-Name", $.cookie("Custom-Auth-Name"));
                XMLHttpRequest.setRequestHeader("Custom-Auth-Key", $.cookie("Custom-Auth-Key"));
                //$(".loading").show();
            },
            complete: function () {
                //$(".loading").hide();
                fn.complete();
            },
            success:function(data, textStatus){
                //成功回调方法增强处理

                fn.success(data, textStatus);
            }
        });
        _ajax(_opt);
    };

})(jQuery);

//判断是否是IE浏览器
function isIE() { //ie?
    if (!!window.ActiveXObject || "ActiveXObject" in window)
        return true;
    else
        return false;
}

///Salt值MD5算法
function hash(key) {
    //定义一个salt值，程序员规定下来的随机字符串
    var salt = "";
    var newKey = key.concat(salt);  //把密码和salt连接
    newKey=$.md5(newKey);  //执行MD5散列
    return newKey;  //返回散列
}

//设置cookie失效时间
var globalCookieTime = new Date();
globalCookieTime.setTime(globalCookieTime.getTime() + (1000 * 60 * 60 * 24 * 7));//cookie保存时间单位毫秒

////////////////////////////////////////////////////////////////////
///获得当前时间
setInterval(function() {
    var now = (new Date()).Format("yyyy-MM-dd hh:mm:ss");
    $('#current-time').text(now);
}, 1000);

///禁止滚动
var scrollFunc=function(e){
    e=e || window.event;
    if(e.wheelDelta && event.ctrlKey){//IE/Opera/Chrome
        event.returnValue=false;
    }else if(e.detail){//Firefox
        event.returnValue=false;
    }
};

/*注册事件*/
if(document.addEventListener){
    document.addEventListener('DOMMouseScroll',scrollFunc,false);
}//W3C
window.onmousewheel=document.onmousewheel=scrollFunc;//IE/Opera/Chrome/Safari

///设置cookie
function setAuthCookie(resp){
    $.cookie("Custom-Auth-Name", $.trim(resp.data["UserCode"]));
    $.cookie("Custom-Auth-Key", $.trim(resp["msg"]));

    $.cookie("Role_name", $.trim(resp.data["Role_name"]));
    $.cookie("UserName", $.trim(resp.data["UserName"]));
    $.cookie("Role_note", $.trim(resp.data["Role_note"]));
    $.cookie("OrgId", $.trim(resp.data["OrgId"]));
    $.cookie("OrgName", $.trim(resp.data["OrgName"]));
    $.cookie("Org", $.trim(resp.data["OrgId"]));
    $.cookie("OperClass", $.trim(resp.data["OperClass"]));
    $.cookie("Role_type", $.trim(resp.data["Role_type"]));
    $.cookie("UserSign", $.trim(resp.data["UserSign"]));
    $.cookie("Role_id", $.trim(resp.data["Role_id"]));

    $.cookie("logName", $.trim(resp.data["logName"]));

}

///清除cookie
function clearAuthCookie(){
    $.cookie("Custom-Auth-Name", null);
    $.cookie("Custom-Auth-Key", null);

    $.cookie("Role_name", null);
    $.cookie("UserName", null);
    $.cookie("Role_note", null);
    $.cookie("OrgId", null);

    $.cookie("OperClass", null);
    $.cookie("Role_type", null);
    $.cookie("UserSign", null);
    $.cookie("Role_id", null);
    $.cookie("logName", null);
}

//获得树表数据
function GetTreeMenuData(myData,j,dataObj) {
    var len = dataObj.length;
    var k = j-1 ;
    for(var i=0;i<len;i++)
    {
        var _tmpData = {};
        var _tableObj = dataObj[i];

        _tmpData["Mpi_id"] = _tableObj["id"] ;
        _tmpData["Mpi_nameTree"] = '<span></span> '+_tableObj["text"] ;
        _tmpData["Mpi_name"] = _tableObj["text"] ;
        _tmpData["Mpi_typeShow"] = _tableObj["Type_name"] ;
        _tmpData["Mpi_type"] = _tableObj["Mpi_type"] ;
        _tmpData["Mpi_url"] = _tableObj["Mpi_url"] ;
        _tmpData["Mpi_action"] = _tableObj["Mpi_action"] ;
        _tmpData["Mpi_controller"] = _tableObj["Mpi_controller"] ;
        _tmpData["Mpi_note"] = _tableObj["Mpi_note"] ;
        _tmpData["Mpi_icon"] = _tableObj["Mpi_icon"] ;
        _tmpData["Mpi_sort"] = _tableObj["Mpi_sort"] ;

        _tmpData["_id"] = j;
        _tmpData["_pid"] = k;
        _tmpData["_class"] = (_tmpData["Mpi_type"]=="0000000004") ? 'level1 child' : 'level2 child';
        _tmpData["_state"] = 'Expand';
        myData[j] = _tmpData;

        j++;
        if( dataObj[i].hasOwnProperty( "children" ) ){
            if(dataObj[i].children.length>0){
                myData[j-1]["_class"]= (myData[j-1]["Mpi_type"]=="0000000004") ? 'level1 hasChild' : 'level2 hasChild';
                j = arguments.callee(myData,j,dataObj[i].children);
            }
        }
    }
    return j;
}
//添加节点，重建树表
function dataAddToMenuTable(_obj,_sourceObj){
    var _tmpData = {};
    var _tableObj = JsonToRow(_sourceObj);

    _tmpData["Mpi_id"] = _tableObj["Mpi_id"] ;
    _tmpData["Mpi_nameTree"] = '<span></span> '+_tableObj["Mpi_name"] ;
    _tmpData["Mpi_name"] = _tableObj["Mpi_name"] ;
    _tmpData["Mpi_typeShow"] = _tableObj["Mpi_typeShow"] ;
    _tmpData["Mpi_type"] = _tableObj["Mpi_type"] ;
    _tmpData["Mpi_url"] = _tableObj["Mpi_url"] ;
    _tmpData["Mpi_action"] = _tableObj["Mpi_action"] ;
    _tmpData["Mpi_controller"] = _tableObj["Mpi_controller"] ;
    _tmpData["Mpi_note"] = _tableObj["Mpi_note"] ;
    _tmpData["Mpi_icon"] = _tableObj["Mpi_icon"] ;
    _tmpData["Mpi_sort"] = _tableObj["Mpi_sort"] ;

    _tmpData["_id"] = _obj.find(' tbody > tr ').length;
    _tmpData["_pid"] = (_obj.bootstrapTable('getSelections').length>0) ? _obj.find(' tbody > tr.selected ').attr("id") : "-1";
    _tmpData["_class"] = (_tmpData["Mpi_type"]=="0000000004") ? 'level1 child' : 'level2 child';
    _tmpData["_state"] = 'Expand';

    var tableData = _obj.bootstrapTable('getData');

    var dataArrayLeft = [];
    var dataArrayRight = [];
    var dataArrayMiddle = [];

    var index = tableData.length-1;
    //更新父节点显示
    if(_obj.bootstrapTable('getSelections').length>0){
        _obj.bootstrapTable('getSelections')[0]["_class"] = 'level1 hasChild' ;
        index = GetTreeLastNode(_obj.find(' tbody > tr.selected '));
    }

    for(var i=0;i<=index;i++){
        dataArrayLeft[i] = tableData[i];
    }

    for(var j=0;j<tableData.length-parseInt(index)-1;j++){
        dataArrayRight[j] = tableData[j+parseInt(index)+1];
    }
    dataArrayMiddle[0] = _tmpData;
    var dataArray = dataArrayLeft.concat(dataArrayMiddle.concat(dataArrayRight));
    _obj.bootstrapTable("load", dataArray);
}

//刷新行数据
function dataBindToMenuTable(_obj,_sourceObj){
    var _tmpData = {};
    var _index = _obj.find("tr.selected").index();
    var _tableObj = JsonToRow(_sourceObj);

    _tmpData["Mpi_id"] = _tableObj["Mpi_id"] ;
    _tmpData["Mpi_nameTree"] = '<span></span> '+_tableObj["Mpi_name"] ;
    _tmpData["Mpi_name"] = _tableObj["Mpi_name"] ;
    _tmpData["Mpi_typeShow"] = _tableObj["Mpi_typeShow"] ;
    _tmpData["Mpi_type"] = _tableObj["Mpi_type"] ;
    _tmpData["Mpi_url"] = _tableObj["Mpi_url"] ;
    _tmpData["Mpi_action"] = _tableObj["Mpi_action"] ;
    _tmpData["Mpi_controller"] = _tableObj["Mpi_controller"] ;
    _tmpData["Mpi_note"] = _tableObj["Mpi_note"] ;
    _tmpData["Mpi_icon"] = _tableObj["Mpi_icon"] ;
    _tmpData["Mpi_sort"] = _tableObj["Mpi_sort"] ;
    _tmpData["_id"] = _obj.find(' tbody > tr.selected ').attr("id") ;
    _tmpData["_pid"] =  _obj.find(' tbody > tr.selected ').attr("pid") ;
    _tmpData["_class"] = _obj.find(' tbody > tr.selected ').attr("class") ;
    //_tmpData["state"] = false;

    //alert(JSON.stringify(_row));
    _obj.bootstrapTable('updateRow', {
        index: _index,
        row: _tmpData
    });
}
///////////////////////////////////////////////////////////////////////////////////////////////////
//生成下拉列表
function FormatSelect(_url,_obj,firstName,_defaultValue,success) {
    $.ajax({
        type: "get",
        url: _url,
        dataType: "json",
        async:false,
        success: function (resp) {
            if(resp)
            {
                FormatSelectOption(_obj,resp.data,firstName,_defaultValue);
                success(resp);
            }
            else{alert("列表数据加载异常！");}
        },
        error:function(){alert("获取下拉列表数据失败！");}
    });
}
//生成下拉列表选项
function FormatSelectOption(selObj,dataObj,firstName,defaultValue) {
    selObj.empty();
    //var option;
    //alert(firstName);
    var option= (firstName!="") ? $("<option>").text(firstName).val("") : "" ;
    selObj.append(option);
    for(var i=0;i<dataObj.length;i++) {
        if(dataObj[i].Mcctype!=undefined){
            if(defaultValue == dataObj[i].Dic_data){
                option = $("<option>").text(dataObj[i].Mcctype+" "+dataObj[i].Mccname).val(dataObj[i].Mcctype).attr("selected", "selected");
            }else{
                option = $("<option>").text(dataObj[i].Mcctype+" "+dataObj[i].Mccname).val(dataObj[i].Mcctype);
            }

        }else if(dataObj[i].id==undefined){
            if(defaultValue == dataObj[i].Dic_data){
                option = $("<option>").text(dataObj[i].Dic_name).val(dataObj[i].Dic_data).attr("selected", "selected");
            }else{
                option = $("<option>").text(dataObj[i].Dic_name).val(dataObj[i].Dic_data);
            }
        }else{
            if(defaultValue == dataObj[i].id){
                option = $("<option>").text(dataObj[i].text).val(dataObj[i].id).attr("selected", "selected");
            }else{
                option = $("<option>").text(dataObj[i].text).val(dataObj[i].id);
            }
        }
        selObj.append(option);
    }
}
//生成下拉列表
function FormatSelectHasABIS(_url,_obj,firstName,_defaultValue,success) {
    $.ajax({
        type: "get",
        url: _url,
        dataType: "json",
        async:false,
        success: function (resp) {
            if(resp)
            {
                FormatSelectOptionHasABIS(_obj,resp.data,firstName,_defaultValue);
                success(resp);
            }
            else{alert("列表数据加载异常！");}
        },
        error:function(){alert("获取下拉列表数据失败！");}
    });
}
//生成下拉列表选项
function FormatSelectOptionHasABIS(selObj,dataObj,firstName,defaultValue) {
    selObj.empty();
    //var option;
    //alert(firstName);
    var option= (firstName!="") ? $("<option>").text(firstName).val("") : "" ;
    selObj.append(option);
    for(var i=0;i<dataObj.length;i++) {
        if(dataObj[i].id==undefined){
            if(defaultValue == dataObj[i].Dic_data){
                option = $("<option>").text(dataObj[i].Dic_name).val(dataObj[i].Dic_data).attr("selected", "selected");
            }else{
                option = $("<option>").text(dataObj[i].Dic_name).val(dataObj[i].Dic_data);
            }
        }else{
            if(defaultValue == dataObj[i].id){
                option = $("<option>").text($.trim(dataObj[i].ABISCode).substr(-4)+" "+dataObj[i].text).val(dataObj[i].id).attr("selected", "selected");
            }else{
                option = $("<option>").text($.trim(dataObj[i].ABISCode).substr(-4)+" "+dataObj[i].text).val(dataObj[i].id);
            }
        }
        selObj.append(option);
    }
}
//设置下拉列表默认值
function SetSelectSelected(_obj,_defaultValue) {
    //_obj.find(" > option").removeAttr('selected');
    if(_defaultValue != ""){
        _obj.find(" > option[value!="+_defaultValue+"]").removeAttr('selected');
        _obj.find(" > option[value="+_defaultValue+"]").attr('selected','selected');
    }else{
        _obj.find(" > option").removeAttr('selected');
    }
}
//下拉列表更新显示域
function refreshSelectShow(_obj,_sourceobj){
    if(_obj.find("option:selected").val()!=""){
        var _value = _obj.find("option:selected").text();
        _sourceobj.val(_value);
    }
}
//表格数据绑定到弹出层
function dataBindToModal(_obj,_sourceobj){
    for(var i=0;i<_obj.serializeArray().length;i++){
        var _name = $.trim(_obj.serializeArray()[i].name);
        var _value = (_sourceobj!=null) ? _sourceobj.bootstrapTable('getSelections')[0][_name] : "" ;
        if(_value==undefined)
        {
            continue;
        }
        if(_value != null ||"SELECT"!=_obj.find("#"+_name).get(0).tagName)
            _obj.find("#"+_name).val($.trim(_value));
    }
}
//数据Ajax绑定到弹出层
function dataAjaxBindToModal(_obj,_sourceobj){
    for(var i=0;i<_obj.serializeArray().length;i++){
        var _name = _obj.serializeArray()[i].name;
        var _value = (_sourceobj!=null) ? _sourceobj[_name] : "" ;
        if(_value != null || "SELECT"!=_obj.find("#"+_name).get(0).tagName)
            _obj.find("#"+_name).val($.trim(_value));
    }
}

//弹出层数据绑定到表格
function dataBindToTable(_obj,_sourceobj){
    var _index = _obj.find("tr.selected").index();
    var _row = JsonToRow(_sourceobj);
    _obj.bootstrapTable('updateRow', {
        index: _index,
        row: _row
    });
}
//弹出层增加记录到表格
function dataAddToTable(_obj,_sourceobj){
    var _row = JsonToRow(_sourceobj);
    _obj.bootstrapTable("append", _row);
}
//从表格删除记录
function dataDelFromTable(_obj){
    var selects = _obj.bootstrapTable('getSelections');
    //更新父节点显示
    var pid = _obj.bootstrapTable('getSelections')[0]["_pid"];
    if(_obj.find(" tbody > tr[pid='"+pid+"'] ").length==1){
        var index = _obj.find(" tbody > tr[id='"+pid+"'] ").attr("data-index");
        var tableData = _obj.bootstrapTable('getData');
        var tmpRow = tableData[index];
        tmpRow["_class"] = "level1 child";
        _obj.bootstrapTable('updateRow', {
            index: index,
            row: tmpRow
        });
    }
    var _state = $.map(selects, function (row) {
        return row.state;
    });
    _obj.bootstrapTable('remove', {
        field: 'state',
        values: _state
    });
}
//json转update需要的格式
function JsonToRow(_obj){
    var _str = {};
    for(var i=0;i<_obj.serializeArray().length;i++){
        var _name = _obj.serializeArray()[i].name;
        _str[_name] = _obj.serializeArray()[i].value;
    }
    return _str;
}
//格式化单选
function dataFormatRadio(_form,_input,_radio){
    var _value = _form.find(' input[name="'+_input+'"] ').val();
    (_value!="") ? _form.find(' input[name="'+_radio+'"][value="'+_value+'"] ').prop('checked', true) : _form.find(' input[name="'+_radio+'"] ').prop('checked', false);
}
//格式化复选
function dataFormatCheck(_form,_input,_check,_allCheck){
    var _value = _form.find(' input[name="'+_input+'"] ').val();
    var _len = (_value.length<=_form.find(' input[name="'+_check+'"]').length) ? _value.length : _form.find(' input[name="'+_check+'"]').length;
    if(_len>0){
        var _boolAll = true;
        for(var i=0;i<_len;i++){
            var _boolCheck = (_value[i]=="1") ;
            _boolAll = _boolAll && _boolCheck;
            _form.find(' input[name="'+_check+'"]')[i].checked = _boolCheck;
        }
        _form.find(' input[name="'+_allCheck+'"]')[0].checked = _boolAll;
    }
    else{
        for(var j=0;j<_form.find(' input[name="'+_check+'"]').length;j++){
            _form.find(' input[name="'+_check+'"]')[j].checked = false;
        }
        _form.find(' input[name="'+_allCheck+'"]')[0].checked = false;
    }
}
//验证全选
function checkAllCheck(_input,_check,_allCheck){
    _check.prop("checked",_allCheck.prop("checked"));
    var _valueAreaMask = "";
    _check.each(function(){
        //_valueAreaMask += ($(this).prop("checked")) ? $(this).val()+"," : "";
        _valueAreaMask += ($(this).prop("checked")) ? "1" : "0";
    });
    _input.val(_valueAreaMask);
}
//验证单个复选
function checkOneCheck(_input,_check,_allCheck){
    var _boolCheck = true;
    var _valueAreaMask = "";
    _check.each(function(){
        _boolCheck = _boolCheck && $(this).prop("checked");
        //_valueAreaMask += ($(this).prop("checked")) ? $(this).val()+"," : "";
        _valueAreaMask += ($(this).prop("checked")) ? "1" : "0";
    });
    _allCheck.prop("checked",_boolCheck);
    _input.val(_valueAreaMask);
}
//获得机构树父元素信息
function GetParentOrg(resp){
    var strId = {};
    //var organLevelName = ['省行','市行','支行','网点'];
    strId["ParentId"] = resp["Id"];
    strId["ShortName"] = resp["Name"];
    strId["OrgLevel"] = parseInt(resp["OrgLevel"])+1;
    strId["OrgLevelName"] = GetLevelName(strId["OrgLevel"]);
    return strId;
}

//获得机构树父元素信息
function GetLevelName(index){
    var organLevelName = ['省行','市行','支行','网点'];
    var Name = (index<=4) ? organLevelName[parseInt(index)-1] : '' ;
    return Name;
}
//var organLevelName = ['省行','市行','支行','网点'];
//设置元素只读
function objFormatReadonly(_form,_objs){
    /*
    for(var i= 0;i< _objs.length;i++){
        _obj = _objs[i];
        _objType = _form.find(' [name="'+_obj+'"] ').attr("type");
        if(_objType == "radio" || _objType == "checkbox" || _objType == undefined ){
            //_form.find(' [name="'+_obj+'"] ').addClass("hidden");
        }else{
            //_form.find(' [name="'+_obj+'"] ').attr("readonly","readonly");
        }
        $('input,select,textarea',$('form[name="validForm"]')).prop('readonly',true);
    }
    */
}

//获得当前树的最后一个节点及序号
function GetTreeLastNode(_obj) {
    var pid = _obj.attr("id");
    var obj = $('#table').find(" tbody > tr[pid='"+pid+"']:last ");
    if(obj.length>0){
        return GetTreeLastNode(obj);
    }
    else{
        return _obj.attr("data-index");
    }
}

//获得树表数据
function GetTreeTableData(myData,j,dataObj) {
    var len = dataObj.length;
    var k = j-1 ;
    for(var i=0;i<len;i++)
    {
        var _tmpData = {};
        _tmpData["organId"] = dataObj[i].id ;
        _tmpData["ABISCode"] = dataObj[i].ABISCode ;
        _tmpData["organTreeName"] = '<span></span> '+dataObj[i].text ;
        _tmpData["organName"] = dataObj[i].text ;
        _tmpData["organLevel"] = dataObj[i].level ;
        _tmpData["organLevelName"] = GetLevelName(dataObj[i].level) ;
        _tmpData["organState"] = dataObj[i].disused ;
        _tmpData["_id"] = j;
        _tmpData["_pid"] = k;
        _tmpData["_class"] = GetLevelClass(dataObj[i].level) + ' hasChild ';
        _tmpData["_state"] = 'Expand';
        myData[j] = _tmpData;
        j++;
        if( dataObj[i].hasOwnProperty( "children" ) ){
            if(dataObj[i].children.length==0){
                //myData[j-1]["_class"]="child";
                myData[j-1]["_class"]= GetLevelClass(dataObj[i].level) + ' child ';
            }
            j = arguments.callee(myData,j,dataObj[i].children);
        }
    }
    return j;
}
//树表收放
function opTree(obj,state) {
    //树型菜单效果
    var pid = obj.attr("id");
    var _state = (state!="") ? state : obj.attr("state") ;
    if(_state == "Collapse"){
        obj.attr("state","Expand");
        obj.find(' > td > span').removeClass("expand");
    }
    else{
        obj.attr("state","Collapse");
        obj.find(' > td > span').addClass("expand");
    }

    $("#table tbody tr[pid='"+pid+"']").each(function(){
        var _obj = $(this);
        if(_state == "Collapse"){
            _obj.show();
        }
        else{
            _obj.hide();

        }
        //opTree(_obj,_state);
    });
}
//获取模板
function getTpls(_url,success,error){
    $.ajax({
        type: "get",
        url: _url,
        success: function (resp) {
            if(resp)
            {
                success(resp);
               /* $("input[required]").parent().prev().append('<span class="glyphicon glyphicon-asterisk red"></span>');
                $("select[required]").parent().prev().append('<span class="glyphicon glyphicon-asterisk red"></span>');*/
                $("input[required]").parent().prev().append('<span class="red">*</span>');
                $("select[required]").parent().prev().append('<span class="red">*</span>');
                $(".modal-content").addClass("dropzone");
                $('.dropzone').draggable();
                $(".modal").attr("data-backdrop","static")
                $("#level11").parent().parent().find('.red').empty();
                $("#MCCType").parent().find(".red").empty();
        }
            else
            {
                alert("模板数据为空！");
            }
        },
        error:function(){
            alert("获取模板数据失败！");
        }
    });
}
//遍历对象属性
function allPrpos(obj) {
    // 用来保存所有的属性名称和值
    var props = "";
    // 开始遍历
    for(var p in obj){
        // 方法
        if(typeof(obj[p])=="function"){
            //obj[p]();
        }else{
            // p 为属性名称，obj[p]为对应属性的值
            props+= p + "=" + obj[p] + "\t";
        }
    }
    // 最后显示所有的属性
    alert(props);
}


/*
* 名称：OrgSelectInit
* 功能: 初始化机构的三级联动下拉列表
* 参数：
*/
function OrgSelectInit(){
    localStorage.orgid= $.cookie("OrgId");
    switch ($.cookie("OperClass")){
        case "1":
            FormatSelect(globalUrl+"api/Site?orgid=910",$("#level1"),"全部","",function(resp){});
            break;
        case "2":
            $("#level1").parent().addClass("hidden");
            $("#level2").empty().parent().css("display","block");
            FormatSelect(globalUrl+"api/Site?orgid="+ $.cookie("OrgId"),$("#level2"),"全部","",function(resp){});
            break;
        case "3":
            $("#level1").parent().addClass("hidden");
            $("#level3").empty().parent().css("display","block");
            FormatSelect(globalUrl+"api/Site?orgid="+ $.cookie("OrgId"),$("#level3"),"全部","",function(resp){});
            break;
        case "4":
            $("#level1,#level2,#level3").parent().addClass("hidden");
            $("#OrgId").val($.cookie("OrgId")).attr("readonly",true).parent().parent().css("display","none");
            $(".custom-selected").addClass("hidden");
            break;
    }
    $("#level1").change(function(){
        $("#level2").empty().parent().css("display","none");
        $("#level3").empty().parent().css("display","none");
        localStorage.orgid=$(this).val();
        if($(this).val()!=""){
            FormatSelect(globalUrl+"api/Site?orgid="+$(this).val(),$("#level2"),"全部","",function(resp){
                if($("#level2 option").length>0)
                {
                    $("#level2").parent().css("display","block");
                }
            });
        }
        else
        {
            localStorage.orgid="910";
        }


    });
    $("#level2").change(function(){
        localStorage.orgid=$(this).val();
        $("#level3").empty().parent().css("display","none");
        if($(this).val()!=""){
            var orgid=$(this).val();
            var orgtext=$(this).find("option:checked").text();
            FormatSelect(globalUrl+"api/Site?orgid="+$(this).val(),$("#level3"),"全部","",function(resp){
                level3=resp;
                if($("#level3 option").length>0)
                {
                    $("#level3").parent().css("display","block");
                }
            });
        }


    });
    $("#level3").change(function(){
        if($(this).val()!=""){
            localStorage.orgid=$(this).val();
        }

    });
}


function getFormData(){
    var formData={};
    formData.customer=getFormDataById("step1");
    formData.cardno={CardNo:$("#CardNo").val()};
    formData.merchant=getFormDataById("step2");
    if($("#MerchantId").val()=="9999")
    {
        delete formData.merchant.MerchantId;
    }
    formData.binddevicecustomer= $.extend(getFormDataById("step3"),getFormDataById("step4"));
    formData.customer.CardNo=undefined;
    console.log(formData);
    console.log(JSON.stringify(formData));
    return formData;
}
function getFormDataById(id)
{
    var names=$("#"+id).find("[name]"),o={};
    for( var i=0;i<names.length;i++)
    {
        $name=$(names[i]);
        o[$name.attr("name")]=$name.val();
    }
    return o;
}
function getModifyFormData(){
    var formData={};
    formData.customer=getModifyFormDataById("step1");
    if($.trim($("#CardNo").val())!=$.trim($('#table').bootstrapTable('getSelections')[0].CardNo))
    {
        formData.cardno={CardNo:$("#CardNo").val()};
    }
    formData.merchant=getModifyFormDataById("step2");
    formData.binddevicecustomer= $.extend(getModifyFormDataById("step3"),getModifyFormDataById("step4"),getModifyFormDataById("step5"));
    delete formData.customer.CardNo;
    delete formData.customer.level11;
    delete formData.customer.level12;
    delete formData.customer.level13;
    delete formData.merchant.IsKh;
    formData.customer.PId=$('#table').bootstrapTable('getSelections')[0].PId;
    if($("#MerchantId").val()!="9999")
    {
        formData.merchant.MerchantId=$("#MerchantId").val();
    }
    else
    {
        delete formData.merchant.MerchantId;
    }
    formData.binddevicecustomer.OrgId=$("#level13").val();
    formData.binddevicecustomer.DeviceId=$('#table').bootstrapTable('getSelections')[0].DeviceId;
    formData.binddevicecustomer.SafeDevId=$('#table').bootstrapTable('getSelections')[0].SafeDevId;
    formData.binddevicecustomer.IsKh=$("#IsKh").val();
    formData.cardno={CardNo:$('#table').bootstrapTable('getSelections')[0].CardNo+","+$("#CardNo").val()}
    formData.binddevicecustomer.ConfirmNote=$('#table').bootstrapTable('getSelections')[0].LID+","+$('#table').bootstrapTable('getSelections')[0].OID+","+$('#table').bootstrapTable('getSelections')[0].CID;

    console.log(formData);
    console.log(JSON.stringify(formData));
    return formData;
}
function getModifyFormDataById(id)
{
    var names=$("#"+id).find("[name]"),o={};
    for( var i=0;i<names.length;i++)
    {
        var $name=$(names[i]);
        /*console.log($.trim($name.val()));
        console.log($.trim($('#table').bootstrapTable('getSelections')[0][$name.attr("name")]));
        console.log($.trim($name.val())!=$.trim($('#table').bootstrapTable('getSelections')[0][$name.attr("name")]));*/
        if($.trim($name.val())!=$.trim($('#table').bootstrapTable('getSelections')[0][$name.attr("name")]))
        {
            o[$name.attr("name")]=$name.val();
        }
    }
    return o;
}

function initCards(data,$select){
    $select.empty();
    for(var i=0;i<data.length;i++)
    {
        var op='<option value="'+data[i].CardNo+'">'+data[i].CardNo+'</option>';
        $select.append(op);
    }
    $select.append('<option value="9999">添加新账号</option>');
}

function initMerchants(data,$select){
    $select.empty();
    for(var i=0;i<data.length;i++)
    {
        var op='<option value="'+data[i].MerchantId+'">'+data[i].MerchantName+'</option>';
        $select.append(op);
    }
    $select.append('<option value="9999">添加新商户</option>');
}

function isValidFields($form,names){
    var flag=true;
    for(var i=0;i<names.length;i++)
    {
        //alert(names[i]+"|"+$form.data('formValidation').isValidField(names[i]));
        $form.data('formValidation').validateField(names[i]);
        var temp=$form.data('formValidation').isValidField(names[i]);
        //alert(names[i]+"|"+temp);
        if(!temp)
        {
            $form.data('formValidation').updateStatus(names[i], "INVALID");
        }
        flag=flag&&temp;
    }
    return flag;
}

function setFieldsValid($form,names){
    for(var i=0;i<names.length;i++)
    {
        $form.data('formValidation').updateStatus(names[i], "VALID");
    }
}

function setFieldsInValid($form,names){
    for(var i=0;i<names.length;i++)
    {
        $form.data('formValidation').updateStatus(names[i], "INVALID");
    }
}

function reloadFields($form,names){
    for(var i=0;i<names.length;i++)
    {
        $form.data('formValidation').removeField(names[i]);
        $form.data('formValidation').addField(names[i]);
    }
}
function resetPlaceholderData($form){
    var phs=$form.find("[placeholder]");
    for(var i=0;i<phs.length;i++)
    {
        $ph=$(phs[i]);
        if($ph.val()==$ph.attr("placeholder"))$ph.val("");
    }
}
var regExpresions={
    id:"^[0-9]{18}$",
    phone:"^[0-9]{11}$"
};
/*var fields={
    CertifiNo:"id",
    Phone:"phone"
};*/
function innitRegularExpression(fields){
    for(var attr in fields){
        $("#"+attr).attr("pattern",regExpresions[fields[attr]]);
    }
}
